<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/21
 * Time: 22:15
 */

namespace api\controllers;


use api\ext\UploadFile;
use api\models\Article;
use corephp\web\Request;

class ArticleController extends Base
{
    public function add()
    {
        $model = new Article();
        $model->data($_POST)->insert();//
        return json_encode([
            'status'=>1
        ]);
    }
    public function detail()
    {
        $id = Request::get('id');
        $model = new Article();
        $Article = $model->where(['id'=>$id])->get();
        return json_encode($Article);
    }
    public function edit()
    {
        $id = Request::post('id');
        $model = new Article();
        $model->data($_POST)->where(['id'=>$id])->update();//
        return json_encode([
            'status'=>1
        ]);
    }
    public function articles()
    {
        $page = (int)Request::get('page',1);
        $page = $page >0 ? $page : 1;
        $limit = 10;
        $start = ($page-1)*$limit;
        $model = new Article();
        $count = $model->where(['deleted'=>0])->count();
        if($count){
            $articles = $model->where(['deleted'=>0])->orderBy(['id'=>'DESC'])->limit([$start,$limit])->select();

        }else{
            $articles=[];
        }

        return json_encode([
            'count'=>$count,
            'list'=>$articles
        ]);
    }
    public function hotArticles()
    {
        $page = (int)Request::get('page',1);
        $page = $page >0 ? $page : 1;
        $limit = 4;
        $start = ($page-1)*$limit;
        $model = new Article();
        $count = $model->where(['deleted'=>0])->count();
        if($count){
            $article = $model->where(['deleted'=>0])->orderBy(['id'=>'DESC'])->limit([$start,$limit])->select();

        }else{
            $article=[];
        }
        return json_encode([
            'count'=>$count,
            'list'=>$article
        ]);
    }

    public function delete()
    {
        $id = Request::get('id');
        (new Article())->where(['id'=>$id])->data(['deleted'=>1])->update();
        return json_encode([
            'status'=>1
        ]);
    }
    public function upload()
    {
        $upload = new UploadFile();// 实例化上传类
        $upload->maxSize  = 3145728 ;// 设置附件上传大小
        $upload->allowExts  = array('jpg', 'png', 'jpeg');// 设置附件上传类型
        $upload->savePath =  'upload/article/';// 设置附件上传目录
        if(!$upload->upload()) {// 上传错误提示错误信息
            $msg = $upload->getErrorMsg();
            $result['status']=0;
            $result['msg'] = $msg;
        }else{// 上传成功
            $imginfo=$upload->getUploadFileInfo();
            $result['status']=1;
            $result['msg'] = $imginfo[0];

        }
        return json_encode($result);
    }
}